from flask import (
    Blueprint, json
)
from blemesh import db, util
from .mesh import login_request
from .error import error_handle
import threading
group = db.Group()
light = db.Light()
bp = Blueprint('group', __name__, url_prefix='/group')
mutex = threading.Lock()

@bp.route('/group_list/',methods=['POST'])
@error_handle
@login_request
def group_list(user_id, req, res):
    mesh_id = req['meshid']
    dbresult = group.groups_of_mesh(mesh_id)
    res['groups'] = []
    if(dbresult):
        length = len(dbresult)
        for i in range(length):
            tmp = dbresult[i]
            groupi = {
                'id': tmp['id'],
                'name': tmp['name'],
                'groupaddress': tmp['group_address']
            }
            res['groups'].append(groupi)
    res['code'] = 0
    res['msg'] = "返回组列表成功"
    return json.dumps(res)

@bp.route('/add_group/',methods=['POST'])
@error_handle
@login_request
def add_group(user_id, req, res):
    groupname = req['name']
    meshid = req['meshid']
    #获取地址到更新地址要加锁
    mutex.acquire()
    dbresult = group.get_group_addr(meshid)
    group_address = dbresult['group_address']
    print("得到的最新的group_address是:", group_address)
    group_address_int = util.hexstr_to_int(group_address)
    new_group_address_int = group_address_int+1
    new_group_address = util.int_to_hexstr(new_group_address_int, 4)
    print("更新的组的地址 = ", new_group_address )
    dbresult = group.update_group_addr(meshid,new_group_address)
    mutex.release()
    if(dbresult):
        dbresult = group.add_group(meshid, groupname, group_address)
        if (dbresult):
            res['code'] = 0
            res['msg'] = "添加组成功！"
            res['group'] = {
                'id': dbresult['id'],
                'name': groupname,
                'groupaddress': group_address
            }
    return json.dumps(res)

@bp.route('/group_info/',methods=['POST'])
@error_handle
@login_request
def group_info(user_id, req, res):
    print("组的详情中的req：",req)
    group_id = req['groupid']
    lights_in = group.lights_in_group(group_id)
    print("lights in :",lights_in )
    lights_out = group.lights_out_group(group_id)

    # res['lightsin'] = lights_in
    # res['lightsout'] = lights_out

    print("lights out :", lights_out)
    if lights_in:
        lenin = len(lights_in)
        for i in range(lenin):
            tmp = lights_in[i]
            tmp['nodeaddress']=tmp['device_address']
            tmp['devicekey'] = tmp['device_key']
    if lights_out:
        lenout = len(lights_out)
        for i in range(lenout):
            tmp = lights_out[i]
            tmp['nodeaddress'] = tmp['device_address']
            tmp['devicekey'] = tmp['device_key']
    res['lightsin'] = lights_in
    res['lightsout'] = lights_out
    res['code'] = 0
    res['msg'] = "返回组详细信息成功！"
    return json.dumps(res)


@bp.route('/rename_group/',methods=['POST'])
@error_handle
@login_request
def rename_group(user_id, req, res):
    print("重命名中的req：", req)
    group_name = req['name']
    group_id = req['groupid']
    dbresult = group.rename_group(group_id, group_name)
    if dbresult:
        res['code'] = 0
        res['msg'] = "重命名成功！"
    else:
        res['msg'] = "重命名时数据库出错！"
    return json.dumps(res)

@bp.route('/delete_group/',methods=['POST'])
@error_handle
@login_request
def delete_group(user_id, req, res):
    group_id = req['groupid']
    group.delete_group(group_id)
    res['msg'] = "删除组成功！"
    res['code'] = 0
    return json.dumps(res)

@bp.route('/group_control/',methods=['POST'])
@error_handle
@login_request
def group_control(user_id, req, res):
    group_id = req['groupid']
    warm = req['warm']
    cold = req['cold']
    red = req['red']
    green = req['green']
    blue = req['blue']
    dbresult = group.group_control(group_id, warm, cold, red, green, blue)
    res['msg'] = "组控成功！"
    res['code'] = 0
    return json.dumps(res)

@bp.route('/group_off/',methods=['POST'])
@error_handle
@login_request
def group_off(user_id, req, res):
    group_id = req['groupid']
    dbresult = group.off(group_id)
    res['msg'] = "关组成功！"
    res['code'] = 0
    return json.dumps(res)


@bp.route('/get_scene_list/',methods=['POST'])
@error_handle
@login_request
def get_scene_list(user_id, req, res):
    group_id = req['groupid']
    res['scenes'] = []
    dbresult = group.scenes_of_group(group_id)
    if dbresult:
        length = len(dbresult)
        for i in range(length):
            tmp = dbresult[i]
            scenei = {
                'id':tmp['id'],
                'name':tmp['name'],
                'cold':tmp['cold'],
                'warm':tmp['warm'],
                'red':tmp['red'],
                'green':tmp['green'],
                'blue':tmp['blue']
            }
            res['scenes'].append(scenei)
    res['code'] = 0
    res['msg'] = "返回场景列表成功！"
    return json.dumps(res)

@bp.route('/get_scene_lights/',methods=['POST'])
@error_handle
@login_request
def get_scene_lights(user_id, req, res):
    scene_id = req['sceneid']
    res['scene_lights'] = group.lights_of_scene(scene_id)
    return json.dumps(res)

@bp.route('/add_scene/',methods=['POST'])
@error_handle
@login_request
def add_scene(user_id, req, res):
    mesh_id = req['meshid']
    group_id = req['groupid']
    name = req['name']
    warm = req['warm']
    cold = req['cold']
    red = req['red']
    green = req['green']
    blue = req['blue']
    dbresult = group.add_scene( mesh_id, group_id, name, warm, cold, red, green, blue)
    #在scene_light表中加入组中所有灯

    if dbresult:
        res['scene'] = {
            'id':dbresult['id'],
            'name':name,
            'warm': warm,
            'cold':cold,
            'red' :red,
            'green':green,
            'blue': blue
        }
        res['code'] = 0
        res['msg'] = "添加场景成功！"
    else:
        res['msg'] = "添加场景时数据库出错！"
    return json.dumps(res)

@bp.route('/edit_scene/',methods=['POST'])
@error_handle
@login_request
def edit_scene(user_id, req, res):
    print("编辑场景的req:",req)
    sceneid = req['sceneid']
    groupid = req['groupid']
    warm = req['warm']
    cold = req['cold']
    red = req['red']
    green = req['green']
    blue = req['blue']
    group.group_control(groupid, warm, cold, red, green, blue)#所有灯的颜色
    print("!!!!!!!!!!!!!!!!!!!!!!!!")
    group.edit_scene(sceneid, warm, cold, red, green, blue)#scene + scene_light的修改
    print("!!!!!!!!!!!!!!!!!!!!!!!!")
    res['msg'] = "编辑场景成功！"
    res['code'] = 0
    return json.dumps(res)

@bp.route('/edit_light_in_scene/',methods=['POST'])
@error_handle
@login_request
def edit_light_in_scene(user_id, req, res):
    sceneid = req['sceneid']
    lightid = req['lightid']
    groupid = req['groupid']
    warm = req['warm']
    cold = req['cold']
    red = req['red']
    green = req['green']
    blue = req['blue']
    light.edit_light(lightid,  cold, warm, red, green, blue)
    group.edit_light_in_scene(sceneid, lightid, groupid, warm, cold, red, green, blue)
    res['msg'] = "编辑场景成功！"
    res['code'] = 0
    return json.dumps(res)

@bp.route('/rename_scene/',methods=['POST'])
@error_handle
@login_request
def rename_scene(user_id, req, res):
    print("编辑场景的req:",req)
    sceneid = req['sceneid']
    name = req['name']
    dbresult = group.rename_scene(sceneid, name)
    if dbresult:
        res['msg'] = "重命名场景成功！"
        res['code'] = 0
    else:
        res['msg'] = "重命名场景时数据库出错！"
    return json.dumps(res)

@bp.route('/apply_scene/',methods=['POST'])
@error_handle
@login_request
def apply_scene(user_id, req, res):
    sceneid = req['sceneid']
    dbresult = group.apply_scene(sceneid)
    print("应用场景数据库返回值：",dbresult)
    if dbresult:
        res['msg'] = "应用场景成功！"
        res['code'] = 0
    else:
        res['msg'] = "应用场景时数据库出错！"
    return json.dumps(res)

@bp.route('/off_scene/',methods=['POST'])
@error_handle
@login_request
def off_scene(user_id, req, res):
    sceneid = req['sceneid']
    dbresult = group.off_scene(sceneid)
    if dbresult:
        res['msg'] = "取消应用场景成功！"
        res['code'] = 0
    else:
        res['msg'] = "取消应用场景时数据库出错！"
    return json.dumps(res)

@bp.route('/delete_scene/',methods=['POST'])
@login_request
def delete_scene(user_id, req, res):
    sceneid = req['sceneid']
    dbresult = group.delete_scene(sceneid)
    if dbresult:
        res['msg'] = "删除场景成功！"
        res['code'] = 0
    else:
        res['msg'] = "删除场景时数据库出错！"
    return json.dumps(res)